﻿namespace Soul.IdentityServer.Infrastructure
{
    internal class ResourceStore : IResourceStore
    {
        private readonly IEnumerable<Resource> _resources;

        public ResourceStore(IEnumerable<Resource> resources)
        {
            _resources = resources;
        }

        public Task<Resources> GetResoucesByScopesAsync(List<string> scopes)
        {
            var resources = new List<Resource>();

            var apiScopes = _resources.OfType<ApiScope>()
                 .Where(a => a.Enabled)
                 .Where(a => scopes.Contains(a.Name))
                 .ToList();
            resources.AddRange(apiScopes);

            var apiResources = _resources.OfType<ApiResource>()
                .Where(a => a.Enabled)
                .Where(a => a.AllowedScopes.Any(scope => scopes.Contains(scope)))
                .ToList();
            resources.AddRange(apiResources);

            var identityResources = _resources.OfType<IdentityResource>()
                .Where(a => a.Enabled)
                .Where(a => scopes.Contains(a.Name))
                .ToList();
            resources.AddRange(identityResources);


            return Task.FromResult(new Resources(resources));
        }

        public Task<List<string>> GetSupportedScopesAsync()
        {
            var scopes = new List<string>();
            scopes.AddRange(_resources.OfType<ApiScope>().Where(a => a.Enabled).Select(s => s.Name));
            scopes.AddRange(_resources.OfType<IdentityResource>().Where(a => a.Enabled).Select(s => s.Name));
            return Task.FromResult(scopes);
        }
    }
}
